package main

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"regexp"
	"strings"
	"time"
)

type KugouMusicNew struct {
	Status  int `json:"status"`
	ErrCode int `json:"err_code"`
	Data    struct {
		HaveAlbum     int    `json:"have_album"`
		AlbumName     string `json:"album_name"`
		Img           string `json:"img"`
		AuthorName    string `json:"author_name"`
		SongName      string `json:"song_name"`
		PlayUrl       string `json:"play_url"`
		PlayBackupUrl string `json:"play_backup_url"`
	} `json:"data"`
}

func (k *KugouMusicNew) getName() string {
	return k.Data.SongName
}

func (k *KugouMusicNew) getAlbumName() string {
	return k.Data.AlbumName
}

func (k *KugouMusicNew) getPic() string {
	return k.Data.Img
}

func (k *KugouMusicNew) getDownloadURL() string {
	return k.Data.PlayUrl
}

func (k *KugouMusicNew) getSinger() string {
	return k.Data.AuthorName
}

func ParseByKuGouNew(music_url string) (music *Music) {

	kg := GetMusicInfo(music_url)

	return &Music{
		Name:     kg.getName(),
		URL:      kg.getDownloadURL(),
		AlbumPic: kg.getPic(),
		Album:    kg.getAlbumName(),
		Singer:   kg.getSinger(),
	}
}

func GetMusicInfo(music_url string) (music KugouMusicNew) {

	// https://wwwapi.kugou.com/play/songinfo?srcappid=2919&clientver=20000&clienttime=1722220149585&mid=3b2014c1c8101821d177b760869fdf67&uuid=3b2014c1c8101821d177b760869fdf67&dfid=1twwYD2A3Yxu1jWOQh05sA9v&appid=1014&platid=4&encode_album_audio_id=av20yscb&token=&userid=0&signature=859ac8907bf984dfeb1709bc9886dc6e
	songInfoUrl := "https://wwwapi.kugou.com/play/songinfo"

	md5Key := "NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt"

	songInfoStr := []string{
		md5Key,
		"appid=1014",
		fmt.Sprintf("clienttime=%d", time.Now().Unix()),
		"clientver=20000",
		"dfid=1twwYD2A3Yxu1jWOQh05sA9v",
		selectMusicUrlFormat(music_url),
		"mid=3b2014c1c8101821d177b760869fdf67",
		"platid=4",
		"srcappid=2919",
		"token=",
		"userid=0",
		"uuid=3b2014c1c8101821d177b760869fdf67",
		md5Key,
	}
	signature := md5.Sum([]byte(strings.Join(songInfoStr, "")))
	md5.New()

	infoFullUrl := fmt.Sprintf("%s?srcappid=2919&clientver=20000&%s&mid=3b2014c1c8101821d177b760869fdf67&uuid=3b2014c1c8101821d177b760869fdf67&dfid=1twwYD2A3Yxu1jWOQh05sA9v&appid=1014&platid=4&%s&token=&userid=0&signature=%s",
		songInfoUrl, songInfoStr[2], songInfoStr[5], fmt.Sprintf("%x", signature))
	fmt.Println(infoFullUrl)
	response := Get(infoFullUrl)

	defer response.Body.Close()
	body, err := io.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(body))
	var k KugouMusicNew

	err = json.Unmarshal(body, &k)
	return k
}

func selectMusicUrlFormat(music_url string) (str string) {
	if strings.Contains(music_url, "song") {
		str = "encode_album_audio_id=" + getMusicIdById(music_url)

	} else {
		str = "hash=" + getMusicIdByHash(music_url)
	}
	return
}

func getMusicIdByHash(music_url string) string {
	response := Get(music_url)
	defer response.Body.Close()
	body, _ := io.ReadAll(response.Body)
	regx := regexp.MustCompile(`"hash":"(\w+)"`)
	songId := regx.FindStringSubmatch(string(body))
	return songId[1]
}

func getAlbumIdByHash(music_url string) string {
	response := Get(music_url)
	defer response.Body.Close()
	body, _ := io.ReadAll(response.Body)
	regx := regexp.MustCompile(`"album_id":"(\w+)"`)
	songId := regx.FindStringSubmatch(string(body))
	return songId[1]
}

func getMusicIdById(music_url string) string {
	parts := strings.SplitN(music_url, "#", 2)
	if len(parts) < 2 {
		return "" // 如果没有 '#' 符号，可能是URL格式不正确
	}
	// 获取哈希部分（第二个参数）
	hash := parts[1]

	return hash // 返回哈希值
}
